#include <omnetpp.h>
#include "ComputingMessages_m.h"  // 包含消息头文件
using namespace omnetpp;
using namespace GPUsharing;

using namespace omnetpp;

class UserNode : public cSimpleModule
{
  protected:
    int nodeId;
    int availablePower;
    virtual void initialize() override;
    virtual void handleMessage(cMessage *msg) override;
};

Define_Module(UserNode);

void UserNode::initialize()
{
    nodeId = par("nodeId");
    availablePower = par("availablePower");
    if (nodeId == 1) { // 假设节点 1 发起请求
        RequestComputingPower *request = new RequestComputingPower("Request");
        request->setRequesterId(nodeId);
        request->setRequiredPower(10);
        send(request, "out");
    }
}

void UserNode::handleMessage(cMessage *msg)
{
    if (auto request = dynamic_cast<RequestComputingPower*>(msg)) {
        // 处理请求消息
        if (availablePower >= request->getRequiredPower()) {
            ResponseComputingPower *response = new ResponseComputingPower("Response");
            response->setResponderId(nodeId);
            response->setHasEnoughPower(true);
            response->setAvailablePower(availablePower);
            send(response, "out");
        } else {
            ResponseComputingPower *response = new ResponseComputingPower("Response");
            response->setResponderId(nodeId);
            response->setHasEnoughPower(false);
            response->setAvailablePower(availablePower);
            send(response, "out");
        }
        delete request;
    } else if (auto response = dynamic_cast<ResponseComputingPower*>(msg)) {
        // 处理响应消息
        if (response->getHasEnoughPower()) {
            EV << "Node " << nodeId << " found a node with enough power." << endl;
            TaskAssignment *assignment = new TaskAssignment("Assignment");
            assignment->setRequesterId(nodeId);
            assignment->setResponderId(response->getResponderId());
            assignment->setTaskId(1);
            assignment->setTaskData("Sample task data");
            send(assignment, "out");
        } else {
            EV << "Node " << nodeId << " did not find a node with enough power." << endl;
        }
        delete response;
    } else if (auto result = dynamic_cast<TaskResult*>(msg)) {
        // 处理任务结果消息
        EV << "Node " << nodeId << " received task result: " << result->getResultData() << endl;
        delete result;
    } else {
        EV_ERROR << "Received unknown message type: " << msg->getClassName() << endl;
        delete msg;
    }
}